//
//  GPPhotosView.m
//  Keping
//
//  Created by 23 on 2017/12/9.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "GPPhotosView.h"
#import "GPPhotosCollectionCell.h"
#import <Photos/Photos.h>

@interface GPPhotosView () <UICollectionViewDelegate, UICollectionViewDataSource>

/**collectionView*/
@property(nonatomic,weak) UICollectionView *collectionView;
/**相册按钮*/
@property(nonatomic,weak) UIButton *photosButton;
/**发送按钮*/
@property(nonatomic,weak) UIButton *sendButton;

/**图片*/
@property(nonatomic,strong) NSMutableArray *images;

/**选中的照片个数*/
@property(nonatomic,assign) NSInteger selectedCount;

@end

@implementation GPPhotosView

static NSString * const Id = @"cell";

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor whiteColor];
        
        //设置
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.itemSize = CGSizeMake(200, 180);
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 180) collectionViewLayout:layout];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.showsVerticalScrollIndicator = NO;
        collectionView.showsHorizontalScrollIndicator = NO;
        [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([GPPhotosCollectionCell class]) bundle:nil] forCellWithReuseIdentifier:Id];
        [self addSubview:collectionView];
        self.collectionView = collectionView;
        
        UIButton *photosButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [photosButton setTitle:@"Album" forState:UIControlStateNormal];
        [photosButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [photosButton addTarget:self action:@selector(photoButtonClicked) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:photosButton];
        self.photosButton = photosButton;
        
        UIButton *sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [sendButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [sendButton setTitle:@"Send" forState:UIControlStateNormal];
        [sendButton addTarget:self action:@selector(sendImages) forControlEvents:UIControlEventTouchUpInside];
        sendButton.enabled = NO;
        [self addSubview:sendButton];
        self.sendButton = sendButton;
        
        
        //设置约束
        [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.mas_equalTo(self);
            make.height.mas_equalTo(180);
        }];
        
        [photosButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self).offset(10);
            make.top.mas_equalTo(self.collectionView.mas_bottom).offset(5);
        }];
        
        [sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self).offset(-10);
            make.top.mas_equalTo(self.collectionView.mas_bottom).offset(5);
        }];
        
        
        //获取相册的数据
        [self loadData];
    }
    return self;
}

#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.images.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    GPPhotosCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:Id forIndexPath:indexPath];
    
    cell.photo = self.images[indexPath.item];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //取出模型
    GPPhotosModel *photo = self.images[indexPath.item];
    photo.selected = !photo.selected;
    
    //计算数量
    if (photo.selected) {
        self.selectedCount++;
    }else{
        self.selectedCount--;
        if (self.selectedCount <= 0 ) {
            self.selectedCount = 0;
        }
    }
    NSString *title = @"Send";
    if (self.selectedCount) {
        title = [NSString stringWithFormat:@"Send(%zd)", self.selectedCount];
    }
    
    self.sendButton.enabled = self.selectedCount;
    [self.sendButton setTitle:title forState:UIControlStateNormal];
    
    //刷新
    [self.collectionView reloadData];
}

#pragma mark - 相册处理
- (void)loadData
{
    
    //获取相机胶卷所有图片
    PHFetchResult *assets = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
    //遍历
    for (PHAsset *asset in assets) {
        
        GPPhotosModel *model = [[GPPhotosModel alloc] init];
        
        
        //取出图片
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(200, 180) contentMode:PHImageContentModeDefault options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            
            model.image = result;
            [self.images addObject:model];
            
        }];
    }
    
    
    [self.collectionView reloadData];
    
}


- (void)show
{
    [self loadData];
}

- (void)hide
{
    [self.images removeAllObjects];
    [self.collectionView reloadData];
}

//发送照片
- (void)sendImages
{
    if ([self.delegate respondsToSelector:@selector(photosView:didSendImages:)]) {
        
        NSMutableArray *arrayM = [NSMutableArray array];
        for (GPPhotosModel *model in self.images) {
            if (model.selected) {
                [arrayM addObject:model];
                model.selected = NO;
            }
        }
        
        self.selectedCount = 0;
        [self.sendButton setTitle:@"Send" forState:UIControlStateNormal];
        [self.collectionView reloadData];
        
        [self.delegate photosView:self didSendImages:arrayM];
    }
}

//点击相册按钮
- (void)photoButtonClicked
{
    if ([self.delegate respondsToSelector:@selector(photosViewDidClickAblumnButton:)]) {
        [self.delegate photosViewDidClickAblumnButton:self];
    }
}


#pragma mark - lazy

- (NSMutableArray *)images
{
    if (_images == nil) {
        _images = [NSMutableArray array];
    }
    return _images;
}





@end

